package com.app.couponsharelife.ui.main.me.bindalipay

import android.content.Intent
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.hwangjr.rxbus.RxBus
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.main.me.withdrawal.WithdrawalActivity
import com.app.couponsharelife.ui.viewmodel.MeViewModel
import com.app.couponsharelife.utils.AppUtils
import com.app.fuquan.data.bean.PageStatus
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_bind_alipay.*
import kotlinx.android.synthetic.main.common_tool_bar_layout.*
import java.util.*
import java.util.concurrent.TimeUnit

class BindAlipayActivity : BaseActivity() {

    override val viewLayoutId: Int get() = R.layout.activity_bind_alipay

    private var mViewModel: MeViewModel? = null

    private var isWithdraw = false
    private var userPhone=""
    private var disposable: Disposable? = null

    private var countDownNum: Int = -1

    override fun initViews() {
        AppUtils.initImmersionBar(this,false)
        isWithdraw = intent.getBooleanExtra("isWithdraw", false)
        userPhone=AppUtils.getString(Contacts.USER_MOBILE, "")
        etPhoneNum.setText(userPhone)
        if (userPhone.isNotEmpty()){
            etPhoneNum.setSelection(userPhone.length)
        }
        initToolBar()
        initEditText()
        initClickEvent()
    }

    private fun initToolBar() {
        ivBack.setOnClickListener { finish() }
        tvToolBarTitle.text = "绑定支付宝"
    }

    private fun initEditText() {
        watchEditText(etName, null)
        watchEditText(etAlipayAccount, null)
        watchEditText(etPhoneNum, null)
        watchEditText(etCheckCode, null)
    }

    private fun initClickEvent() {
        tvSendCheckCode.setOnClickListener {
            bindAlipayCheckCode()
        }
        tvConfirmBindBtn.setOnClickListener {
            bindAlipay()
        }
    }

    private fun bindAlipayCheckCode() {
        if (TextUtils.isEmpty(etPhoneNum.text)) {
            showToastMsg("请输入手机号")
            return
        }
        if (TextUtils.isEmpty(etName.text)) {
            showToastMsg("请输入姓名")
            return
        }
        if (TextUtils.isEmpty(etAlipayAccount.text)) {
            showToastMsg("请输入支付宝号")
            return
        }
        val map = HashMap<String, String>()
        map["mobile"] = etPhoneNum.text.toString().trim()
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        mViewModel?.freshSendCheckCode(map, true)
    }

    private fun bindAlipay() {
        if (TextUtils.isEmpty(etName.text)) {
            showToastMsg("请输入姓名")
            return
        }
        if (TextUtils.isEmpty(etAlipayAccount.text)) {
            showToastMsg("请输入支付宝账号")
            return
        }
        if (TextUtils.isEmpty(etPhoneNum.text)) {
            showToastMsg("请输入手机号")
            return
        }
        if (TextUtils.isEmpty(etCheckCode.text)) {
            showToastMsg("请输入验证码")
            return
        }
        val map = HashMap<String, String>()
//        map["accountId"]
        map["userId"] = AppUtils.getString(Contacts.USERID, "")
        map["name"] = etName.text.toString().trim()
        map["account"] = etAlipayAccount.text.toString().trim()
        map["mobile"] = etPhoneNum.text.toString().trim()
        map["code"] = etCheckCode.text.toString().trim()
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        mViewModel?.freshBindAlipay(map, true)
    }

    override fun initViewModel() {
        if (mViewModel == null) mViewModel = ViewModelProviders.of(this).get(MeViewModel::class.java)
        if (!mViewModel!!.sendCheckCode()!!.hasObservers()) {
            mViewModel!!.sendCheckCode()!!.observe(this, Observer {
                if (it == null) {
                    dismissProgressDialog()
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                        showProgressDialog("请稍候")
                    }
                    PageStatus.Error -> {
                        dismissProgressDialog()
                        mViewModel!!.freshSendCheckCode(hashMapOf(), false)
                        showToastMsg(parseErrorDate(it.error!!.message).tip)
                    }
                    PageStatus.Empty -> {
                        dismissProgressDialog()
                        mViewModel!!.freshSendCheckCode(hashMapOf(), false)
                        showToastMsg("数据出错啦")
                    }
                    PageStatus.Content -> {
                        dismissProgressDialog()
                        mViewModel!!.freshSendCheckCode(hashMapOf(), false)
                        if (it.data!!.code == 200) {
                            sendCheckCodeSuccess()
                        } else {
                            showToastMsg("发送失败")
                        }
                    }
                }
            })
            mViewModel!!.bindAlipay()!!.observe(this, Observer {
                if (it == null) {
                    dismissProgressDialog()
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                        showProgressDialog("请稍候")
                    }
                    PageStatus.Error -> {
                        dismissProgressDialog()
                        mViewModel!!.freshBindAlipay(hashMapOf(), false)
                        showToastMsg(parseErrorDate(it.error!!.message).tip)
                    }
                    PageStatus.Empty -> {
                        dismissProgressDialog()
                        mViewModel!!.freshBindAlipay(hashMapOf(), false)
                        showToastMsg("数据出错啦")
                    }
                    PageStatus.Content -> {
                        dismissProgressDialog()
                        mViewModel!!.freshBindAlipay(hashMapOf(), false)
                        if (it.data!!.code == 200) {
                            showToastMsg("绑定成功")
                            if (isWithdraw) {
                                startActivity(Intent(this, WithdrawalActivity::class.java))
                            }
                            RxBus.get().post("mefrg_fraeshdata", "")
                            finish()
                        } else {
                            showToastMsg("绑定失败")
                        }
                    }
                }
            })
        }
    }

    private fun sendCheckCodeSuccess() {
        countDownNum = 59
        tvCheckCodeNum.visibility = View.VISIBLE
        tvSendCheckCode.visibility = View.INVISIBLE
        tvSendCheckCode.isClickable = false
        disposable = Observable.interval(0, 1, TimeUnit.SECONDS)//10s 倒计时
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ aLong ->
                    if (countDownNum < 0)
                        goAhead()
                    else {
                        tvCheckCodeNum.text = "${countDownNum}s后重发"
                        countDownNum--
                    }
                }) { goAhead() }
    }

    private fun goAhead() {
        tvCheckCodeNum.visibility = View.INVISIBLE
        tvSendCheckCode.visibility = View.VISIBLE
        tvSendCheckCode.isClickable = true
        disposable?.dispose()
        disposable == null
    }

    override fun onDestroy() {
        AppUtils.destroyImmersionBar(this)
        if (disposable != null && !disposable!!.isDisposed) {
            disposable?.dispose()
            disposable == null
        }
        super.onDestroy()
    }

    private fun watchEditText(editText: EditText, imageView: ImageView?) {
        editText.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                if (TextUtils.isEmpty(s)) {
                    imageView?.visibility = View.INVISIBLE
                    imageView?.isClickable = false
                } else {
                    imageView?.visibility = View.VISIBLE
                    imageView?.isClickable = true
                }
                checkTotalEdit()
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })
    }

    private fun checkTotalEdit() {
        if (!TextUtils.isEmpty(etName.text) &&
                !TextUtils.isEmpty(etAlipayAccount.text) &&
                !TextUtils.isEmpty(etPhoneNum.text) &&
                !TextUtils.isEmpty(etCheckCode.text)) {
            tvConfirmBindBtn.setBackgroundResource(R.drawable.btn_bg1)
        } else {
            tvConfirmBindBtn.setBackgroundResource(R.drawable.btn_bg2)
        }
    }
}
